/*
 * @Author: Nic
 * @Date: 2023-02-11 23:28:26
 * @LastEditTime: 2023-02-12 10:49:38
 * @LastEditors: Nic
 * @Description:
 * @FilePath: /mahjong-scorer/src/router/index.ts
 */
import { setupLayouts } from 'virtual:generated-layouts'
import { createRouter, createWebHashHistory } from 'vue-router'
import NProgress from 'nprogress'
import generatedRoutes from '~pages'
import 'nprogress/nprogress.css'

const routes = setupLayouts(generatedRoutes)
const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

const getToken = () => {
  return localStorage.getItem('playerID')
}

NProgress.configure({ showSpinner: false })
// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 进度条
  NProgress.start()
  //   next()
  // 具体业务逻辑判断
  if (getToken()) {
    // 已登录且要跳转的页面是登录页
    if (to.path === '/login') {
      console.log('已登录且要跳转的页面是登录页')
      //   next({ path: '/' })
      NProgress.done()
    }
    else {
      // 路由、菜单加载ok
      next()
    }
  }
  else {
    if (to.path === '/login') {
      next()
    }
    else {
      // 没有token
      next(`/login?redirect=${to.fullPath}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 关闭进度条
  NProgress.done()
})

export default router
